<template>
  <div class="pagination">

    
    <button 
        :disabled="pageNo === 1 "
        @click="$emit('newPage' , pageNo - 1)"
    >上一页</button>

    <button
        :class="{active: pageNo === 1}"
        @click="$emit('newPage' , 1)"
        v-show="startEndPage.start !== 1 "
    >1</button>

    <button v-show="startEndPage.start > 2 ">···</button>

    <button
        v-for="page in startEndArr" :key="page"
        :class="{active: pageNo === page }"
        @click="$emit('newPage' , page)"
    >{{page}}</button>

    <button v-show="startEndPage.end < totalPages -1 ">···</button>

    <button
        :class="{active: pageNo === totalPages}"
        @click="$emit('newPage' , totalPages)"
        v-show="startEndPage.end  !== totalPages"
    >{{totalPages}}</button>

    <button
        :disabled="pageNo === totalPages"
        @click="$emit('newPage' , pageNo +1 )"
    >下一页</button>



    <button style="margin-left: 30px">共 {{total}} 条</button>
  </div>
</template>

<script>
export default {
  name: "Pagination",
  props: ["pageNo" , "totalPages" , "continuePage" , "total"],

  computed:{
    //v-for 和v-if不能用在同一个标签 所以计算出要显示的元素
    startEndArr(){
        let arr = []
        //遍历结束页取出需要的值
        for(let i = 1; i <= this.startEndPage.end ; i++){
            if(i >= this.startEndPage.start){
                arr.push(i)
            }
        }

        return arr
    },


    //根据当前页和总页数和连续页计算出 起始页和结束页
    startEndPage(){
        const {pageNo , totalPages , continuePage} = this
        //定义初始值
        let start,end = ""

        //1.如果总页数小于等于连续页 则起始页为1 结束页为总页数
        if(totalPages <= continuePage){
            start = 1
            end = continuePage
        }else{
        //2.如果总页数大于连续页 则正常计算起始和结束页
            start = pageNo - Math.floor(continuePage/2)
            end = pageNo + Math.floor(continuePage/2)

            //3.如果起始页小于1 则设置起始页固定为1,结束页固定为连续页的结束
            if(start < 1){
                start = 1
                end = continuePage
            }
            //4.如果结束页大于总页数 则设置结束页固定为总页数,起始页为总页数减连续页加1
            if(end > totalPages){
                end = totalPages
                start = totalPages - continuePage + 1
            }
        }

        return {start , end}
    }

  },
  
};
</script>

<style lang="less" scoped>
.pagination {
  button {
    margin: 0 5px;
    background-color: #f4f4f5;
    color: #606266;
    outline: none;
    border-radius: 2px;
    padding: 0 4px;
    vertical-align: top;
    display: inline-block;
    font-size: 13px;
    min-width: 35.5px;
    height: 28px;
    line-height: 28px;
    cursor: pointer;
    box-sizing: border-box;
    text-align: center;
    border: 0;

    &[disabled] {
      color: #c0c4cc;
      cursor: not-allowed;
    }

    &.active {
      cursor: not-allowed;
      background-color: #409eff;
      color: #fff;
    }
  }
}
</style>